<?php

if(false === function_exists('lcfirst')){
    /**
     * Make a string's first character lowercase
     * @param string $str
     * @return string the resulting string.
     */
    function lcfirst( $str ) {
        $str[0] = strtolower($str[0]);
        return (string)$str;
    }
}

class Acl{

    protected $accountAssgnedUserId;

    public function getCityUsersWhere(&$fieldDefs, $userId, $moduleName){
        $requestModule = $_REQUEST['module'];
        $assignedField = '';
        if(isset($fieldDefs['assigned_user_id'])){
           $assignedField = 'assigned_user_id';
        }else if(isset($fieldDefs['created_by'])){
            $assignedField = 'created_by';
        }
        if($moduleName == 'Accounts'){
            return lcfirst($moduleName).'.city_id IN ( SELECT grp_city_id FROM grp_cities_users WHERE user_id = "'.$userId.'")';
        }else if($moduleName == 'Contacts' || $moduleName == 'Opportunities'){
            $cityIds = '"'.implode('", "', $this->getUserCitiesIds($userId)).'"';
            return "accounts.city_id IN (".$cityIds.")";
        }else if($moduleName == 'Meetings' || $moduleName == 'Calls'){
            $sqlPart = lcfirst($moduleName).'.parent_id IN (
                SELECT c.id FROM contacts c
                INNER JOIN accounts_contacts ac ON ac.contact_id=c.id
                INNER JOIN accounts a ON a.id=ac.account_id
                WHERE ';
            if($requestModule ==  $moduleName){//meetings or calls
                $sqlPart .= '(a.city_id IN ( SELECT grp_city_id FROM grp_cities_users WHERE user_id = "'.$userId.'") )
                    OR '.lcfirst($moduleName).'.created_by = "'.$userId.'" )';
            }else{//history
                if($requestModule == 'Accounts'){
                    $sqlPart .= ' a.id= "'.$_REQUEST['record'].'" ';
                    $sqlPart .= ' AND ('.lcfirst($moduleName).'.status = "Held" OR '.lcfirst($moduleName).'.status = "Not Held"))';
                }
                if($requestModule == 'Contacts'){
                    $sqlPart = lcfirst($moduleName).'.parent_id = "'.$_REQUEST['record'].'"';
                    $sqlPart .= ' AND ('.lcfirst($moduleName).'.status = "Held" OR '.lcfirst($moduleName).'.status = "Not Held")';
                }
            }
            return $sqlPart;
        } else{
            if(!empty($assignedField)){
                $where = lcfirst($moduleName).'.'.$assignedField.' IN ';
                $where .= '( SELECT user_id FROM grp_cities_users WHERE grp_city_id = ';
                $where .= '( SELECT grp_city_id FROM grp_cities_users WHERE user_id = "'.$userId.'" LIMIT 1 ))';

                return $where;
            }
        }

        return '';
    }

    public function isUserAccountManager($userId){
        $roleName = 'Account Manager';
        $roleId = "6e9e9053-007d-cdc1-ff24-4bc43bc4fe84";
        return $this->isUserInRole($userId, $roleName, $roleId);
//        if( isset($_SESSION['ACL'][$userId]['account_manager'])){
//            if(!is_null($_SESSION['ACL'][$userId]['account_manager'])){
//                return $_SESSION['ACL'][$userId]['account_manager'];
//            }
//        }
//        $userRolesArr = ACLRole::getUserRoles($userId, false);
//
//        if(!empty($userRolesArr)){
//            foreach($userRolesArr as $userRole){
//                if($userRole->name == 'Account Manager' || $userRole->id == '6e9e9053-007d-cdc1-ff24-4bc43bc4fe84'){
//                    $flag = count($userRolesArr) == 1;
//                    $_SESSION['ACL'][$userId]['account_manager'] = $flag;
//                    return $flag;
//                }
//            }
//        }
//
//        $_SESSION['ACL'][$userId]['account_manager'] = false;
//        return false;
    }
    
    public function isUserInResearchRole($userId){
        $roleName = 'Research';
        $roleId = "9d83f93f-beb7-11e0-babd-d8b606f9d028";
        return $this->isUserInRole($userId, $roleName, $roleId);
    }

        /**
     * Checks if user is in passed role params
     * Usere has to be only in one role
     * @param string $userId - user id
     * @param string $roleName - "Account Manager" name form acl_roles table
     * @param string $roleId - id from acl_roles table
     * @return bool
     */
    protected function isUserInRole($userId, $roleName, $roleId = null){
        $roleNamArr = str_replace(" ", "_", $roleName);

        if( isset($_SESSION['ACL'][$userId][$roleNamArr])){
            if(!is_null($_SESSION['ACL'][$userId][$roleNamArr])){
                return $_SESSION['ACL'][$userId][$roleNamArr];
            }
        }
        $userRolesArr = ACLRole::getUserRoles($userId, false);

        if(!empty($userRolesArr)){
            foreach($userRolesArr as $userRole){
                if($userRole->name == $roleName || $userRole->id == $roleId){
                    $flag = count($userRolesArr) == 1;
                    $_SESSION['ACL'][$userId][$roleNamArr] = $flag;
                    return $flag;
                }
            }
        }

        $_SESSION['ACL'][$userId][$roleNamArr] = false;
        return false;
    }

    public function checkUserRecordAccess($currentUserId, $recordOwnerId){
        //pobiera wszystkich uzytkownik z miast do ktorych przypisany jest obecny uzytkownik
        $sql = 'SELECT user_id
            FROM grp_cities_users WHERE grp_city_id IN
            (SELECT grp_city_id FROM grp_cities_users WHERE user_id = "'.$currentUserId.'")';

        $result = $GLOBALS['db']->query($sql);
        while($row = $GLOBALS['db']->fetchByAssoc($result) ){
                if($recordOwnerId == $row['user_id']){
                    return true;
                }
        }

        return false;
    }

    public function getUserCitiesIds($userId){
        if(isset($_SESSION['ACL'][$userId]['citiesIds'])){
            if(!is_null($_SESSION['ACL'][$userId]['citiesIds'])){
                return $_SESSION['ACL'][$userId]['citiesIds'];
            }
        }

        $cities = array();
        $sql = 'SELECT grp_city_id FROM grp_cities_users WHERE user_id = "'.$userId.'"';
        $result = $GLOBALS['db']->query($sql);
        while($row = $GLOBALS['db']->fetchByAssoc($result) ){
            $cities[] = $row['grp_city_id'];
        }

        $_SESSION['ACL'][$userId]['citiesIds'] = $cities;
        return $cities;
    }

    /**
     * Sprawdza dostep do rekordu w module Accounts
     * @param <type> $beanCityId
     * @param <type> $currentUserId
     * @return <type>
     */
    public function checkAccountsAccess($beanCityId, $currentUserId){
        foreach($this->getUserCitiesIds($currentUserId) as $cityId){
            if($beanCityId == $cityId){
                return true;
            }
        }
        return false;
    }
    //pobiera city_id partnera, do ktorego jest przypisany kontakt i porownuje z city id zalogowanego uzytkownika
    public function checkContactsDetialViewAccess($beanId, $currentUserId){
        $sql = "SELECT a.city_id, a.assigned_user_id FROM accounts a, accounts_contacts ac
            WHERE  ac.account_id = a.id AND ac.contact_id = '$beanId' LIMIT 1";
        $result = $GLOBALS['db']->query($sql);
        $row = $GLOBALS['db']->fetchByAssoc($result);

        $this->accountAssgnedUserId = $row['assigned_user_id'];
        foreach($this->getUserCitiesIds($currentUserId) as $cityId){
            if($row['city_id'] == $cityId){
                return true;
            }
        }
        return false;
    }

    public function checkContactsEditViewAccess($beanId, $currentUserId){
        if(is_null($beanId)){//tworzenie kontaktu
            return true;
        }
        if($this->checkContactsDetialViewAccess($beanId, $currentUserId)){
            return $this->accountAssgnedUserId == $currentUserId;
        }
        return false;
    }

    public function checkActivitiesDetialViewAccess($beanId, $beanCreatedBy, $currentUserId, $moduleTable = 'meetings'){
        //var_dump($beanCreatedBy);
        if($beanCreatedBy == $currentUserId){
           return true; 
        }
        $sql = "SELECT DISTINCT a.city_id, a.assigned_user_id
            FROM accounts a, accounts_contacts ac, $moduleTable mt
            WHERE  ac.account_id = a.id AND ac.contact_id = mt.parent_id
            AND mt.id='$beanId' LIMIT 1";
        $result = $GLOBALS['db']->query($sql);
        $row = $GLOBALS['db']->fetchByAssoc($result);

        $this->accountAssgnedUserId = $row['assigned_user_id'];
        foreach($this->getUserCitiesIds($currentUserId) as $cityId){
            if($row['city_id'] == $cityId){
                return true;
            }
        }
        return false;
    }

    public function checkActivitiesEditViewAccess($beanId, $beanCreatedBy, $currentUserId, $moduleTable = 'meetings'){
        if(is_null($beanId)){//tworzenie meetingu
            return true;
        }
        if($beanCreatedBy == $currentUserId){
           return true;
        }
        if($this->checkActivitiesDetialViewAccess($beanId, $currentUserId, $moduleTable)){
            return $this->accountAssgnedUserId == $currentUserId;
        }
        return false;
    }

    public function checkOpportunitiesDetialViewAccess($beanId, $currentUserId){
        $sql = "SELECT DISTINCT a.city_id, a.assigned_user_id
            FROM accounts a, accounts_opportunities ao, opportunities o
            WHERE  ao.account_id = a.id AND ao.opportunity_id = o.id
            AND o.id='$beanId' LIMIT 1";
        $result = $GLOBALS['db']->query($sql);
        $row = $GLOBALS['db']->fetchByAssoc($result);

        $this->accountAssgnedUserId = $row['assigned_user_id'];
        foreach($this->getUserCitiesIds($currentUserId) as $cityId){
            if($row['city_id'] == $cityId){
                return true;
            }
        }
        return false;
    }
    public function checkOpportunitiesEditViewAccess($beanId, $currentUserId){
        if(is_null($beanId)){//tworzenie meetingu
            return true;
        }
        if($this->checkOpportunitiesDetialViewAccess($beanId, $currentUserId)){
            return $this->accountAssgnedUserId == $currentUserId;
        }
        return false;
    }
}

?>
